<!-- V-webapp/src/views/ProductsView.vue -->
<template>
  <div class="products-container">
    <!-- 顶部导航 -->
    <div class="page-header">
      <el-button @click="$router.back()" class="back-btn" type="primary" link>
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h2>周边商城</h2>
      <div class="header-actions">
        <el-button @click="goToCart" type="primary" link>
          <el-icon><ShoppingCart /></el-icon>
          <el-badge v-if="cartCount > 0" :value="cartCount" class="cart-badge"></el-badge>
        </el-button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading && products.length === 0" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 空状态 -->
    <div v-else-if="products.length === 0" class="empty-container">
      <el-empty description="暂无商品">
        <el-button type="primary" @click="fetchProducts(true)">
          重新加载
        </el-button>
      </el-empty>
    </div>

    <!-- 商品列表 -->
    <div v-else class="products-list">
      <div 
        v-for="product in products" 
        :key="product.id" 
        class="product-card"
        @click="goToProductDetail(product.id)"
      >
        <div class="product-image">
          <el-image 
            :src="getProductImage(product)" 
            fit="cover"
            class="image"
            :alt="product.name"
          >
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
          <div v-if="product.stock === 0" class="sold-out-tag">已售罄</div>
        </div>
        
        <div class="product-info">
          <h3 class="product-name">{{ product.name }}</h3>
          <p class="product-desc">{{ product.description }}</p>
          <div class="product-meta">
            <span class="product-price">¥{{ product.price }}</span>
            <span class="product-stock">库存: {{ product.stock }}</span>
          </div>
          <div class="product-actions">
            <el-button 
              type="primary" 
              size="small" 
              :disabled="product.stock === 0 || !isLoggedIn"
              @click.stop="addToCartHandler(product)" 
            >
              <el-icon><Plus /></el-icon>
              {{ isLoggedIn ? '加入购物车' : '请先登录' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div class="load-more">
      <el-button 
        v-if="hasMore && !loading" 
        @click="loadMore"
        type="primary"
        link
      >
        加载更多
      </el-button>
      <div v-else-if="!hasMore" class="no-more">没有更多商品了</div>
      <div v-else class="loading-more">加载中...</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, ShoppingCart, Picture, Plus } from '@element-plus/icons-vue'
import { getProducts } from '@/api/products'
import { addToCart } from '@/api/cart'  // 修复：从 cart API 导入

// 导入本地商品图片
import julyDream from '@/assets/images/七月梦境.jpg'
import julyBadge from '@/assets/images/七月吧唧.jpg'
import mousePad from '@/assets/images/鼠标垫.jpg'
import zhaotaiyang from '@/assets/images/赵太阳立牌.jpg'
import defaultProductImg from '@/assets/images/S2.jpg'

interface Product {
  id: number
  name: string
  description: string
  price: number
  stock: number
  stock_quantity?: number
  cover_image?: string
  product_images?: Array<{
    image_url: string
  }>
  anchor?: {
    anchor_name: string
  }
}

const router = useRouter()
const products = ref<Product[]>([])
const loading = ref(false)
const hasMore = ref(true)
const page = ref(1)
const pageSize = 10
const cartCount = ref(0)

// 图片映射表
const imageMap = {
  '七月梦境.jpg': julyDream,
  '七月吧唧.jpg': julyBadge,
  '鼠标垫.jpg': mousePad,
  '赵太阳立牌.jpg': zhaotaiyang,
  'S2.jpg': defaultProductImg
}

// 计算登录状态
const isLoggedIn = computed(() => {
  return !!localStorage.getItem('token')
})

// 获取商品图片 - 修复逻辑
const getProductImage = (product: Product) => {
  console.log('🖼️ 商品图片信息:', {
    productId: product.id,
    cover_image: product.cover_image,
    product_images: product.product_images
  })
  
  // 1. 优先使用后端返回的完整图片URL
  if (product.cover_image && product.cover_image.startsWith('/uploads/')) {
    const fullUrl = `http://localhost:3000${product.cover_image}`
    console.log('✅ 使用后端图片URL:', fullUrl)
    return fullUrl
  }
  
  // 2. 其次使用 product_images 中的图片
  if (product.product_images && product.product_images.length > 0) {
    const firstImage = product.product_images[0]
    if (firstImage.image_url.startsWith('/uploads/')) {
      const fullUrl = `http://localhost:3000${firstImage.image_url}`
      console.log('✅ 使用商品图片列表URL:', fullUrl)
      return fullUrl
    }
  }
  
  // 3. 最后使用本地映射（兼容旧数据）
  if (product.cover_image && imageMap[product.cover_image]) {
    console.log('📁 使用本地映射图片:', product.cover_image)
    return imageMap[product.cover_image]
  }
  
  // 4. 默认图片
  console.log('🔄 使用默认图片')
  return defaultProductImg
}

// 获取商品列表
const fetchProducts = async (reset = false) => {
  if (loading.value) return
  
  loading.value = true
  try {
    console.log('🛍️ 开始加载商品数据...')
    
    const params = {
      page: reset ? 1 : page.value,
      limit: pageSize
    }
    
    const response = await getProducts(params)
    console.log('✅ 商品API响应:', response)
    
    // 修复：直接使用 response.data 而不是 response.data.products
    const productList = response.data || []
    
    if (reset) {
      products.value = productList
      page.value = 2 // 重置后下一页是第2页
    } else {
      products.value = [...products.value, ...productList]
    }
    
    // 修复：根据实际返回数据判断是否有更多
    hasMore.value = productList.length === pageSize
    
    console.log(`✅ 加载了 ${productList.length} 个商品，总共 ${products.value.length} 个`)
    
  } catch (error) {
    console.error('❌ 获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
    
    // 使用模拟数据作为后备
    if (reset && products.value.length === 0) {
      products.value = generateMockProducts()
      ElMessage.info('使用模拟数据展示')
    }
  } finally {
    loading.value = false
  }
}

// 生成模拟商品数据
const generateMockProducts = () => {
  return Array.from({ length: 6 }, (_, index) => ({
    id: index + 1,
    name: `虚拟商品 ${index + 1}`,
    description: `这是第 ${index + 1} 个虚拟商品的描述信息，包含详细的产品特性介绍`,
    price: Math.floor(Math.random() * 200) + 50,
    stock: Math.floor(Math.random() * 20),
    cover_image: `S2.jpg`, // 使用默认图片
    product_images: []
  }))
}

// 获取商品库存 - 修复逻辑
const getProductStock = (product: Product) => {
  return product.stock || product.stock_quantity || 0
}

// 跳转到商品详情
const goToProductDetail = (productId: number) => {
  router.push(`/product/${productId}`)
}

// 跳转到购物车
const goToCart = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  router.push('/cart')
}

// 加入购物车 - 完全重写
const addToCartHandler = async (product: Product) => {
  // 检查登录状态
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    console.log('🛒 添加商品到购物车:', product.id)
    console.log('🔑 使用Token:', token.substring(0, 20) + '...')
    
    // 使用正确的API调用
    const response = await addToCart({
      product_id: product.id,
      quantity: 1
    })
    
    console.log('✅ 加入购物车响应:', response)
    ElMessage.success('已加入购物车')
    
    // 更新购物车数量
    cartCount.value += 1
    
  } catch (error: any) {
    console.error('❌ 加入购物车失败:', error)
    
    // 详细错误信息
    if (error.response) {
      console.error('错误详情:', {
        status: error.response.status,
        statusText: error.response.statusText,
        data: error.response.data
      })
      
      if (error.response.status === 401) {
        ElMessage.error('登录已过期，请重新登录')
        localStorage.removeItem('token')
        router.push('/login')
      } else if (error.response.status === 404) {
        ElMessage.error('购物车功能暂不可用')
      } else {
        const errorMsg = error.response.data?.message || '加入购物车失败'
        ElMessage.error(errorMsg)
      }
    } else if (error.request) {
      console.error('网络请求失败:', error.request)
      ElMessage.error('网络连接失败，请检查后端服务')
    } else {
      ElMessage.error('加入购物车失败: ' + error.message)
    }
  }
}

// 加载更多
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    page.value += 1
    fetchProducts()
  }
}

// 获取购物车数量
const fetchCartCount = async () => {
  if (!isLoggedIn.value) return
  
  try {
    // 这里需要根据你的购物车API来获取数量
    // 暂时设置为0
    cartCount.value = 0
  } catch (error) {
    console.error('获取购物车数量失败:', error)
  }
}

onMounted(() => {
  fetchProducts(true)
  fetchCartCount()
})
</script>

<style scoped>
.products-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 16px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  color: white;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.cart-badge {
  position: absolute;
  top: -5px;
  right: -5px;
}

.loading-container,
.empty-container {
  padding: 40px 0;
}

.products-list {
  display: grid;
  gap: 16px;
}

.product-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  display: flex;
  gap: 12px;
}

.product-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.product-image {
  position: relative;
  width: 100px;
  height: 100px;
  flex-shrink: 0;
}

.product-image .image {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 8px;
  color: #999;
}

.sold-out-tag {
  position: absolute;
  top: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.product-name {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
}

.product-desc {
  margin: 0;
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  font-size: 18px;
  font-weight: 700;
  color: #ff4757;
}

.product-stock {
  font-size: 12px;
  color: #999;
}

.product-actions {
  display: flex;
  justify-content: flex-end;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

.no-more, .loading-more {
  text-align: center;
  color: white;
  font-size: 14px;
  padding: 20px 0;
}
</style>